package edu.gdkm.ssm.controller;

import edu.gdkm.ssm.domain.Permission;
import edu.gdkm.ssm.domain.Role;
import edu.gdkm.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @GetMapping("findAll.do")
    public ModelAndView findAll() throws Exception{
        List<Role> roleList = roleService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }

    @PostMapping("save.do")
    public String save(Role role){
        this.roleService.save(role);
        return "redirect:findAll.do";
    }

    @GetMapping("findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id") String roleId) throws Exception{
        Role role = this.roleService.findById(roleId);
        List<Permission> permissions = this.roleService.findOtherPermissions(roleId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("role", role);
        modelAndView.addObject("permissionList", permissions);
        modelAndView.setViewName("role-permission-add");
        return modelAndView;
    }

    @PostMapping("addPermissionToRole.do")
    public String addRoleToUser(@RequestParam(name = "roleId", required = true) String roleId,
                                @RequestParam(name = "ids", required = true) String[] permissionIds) throws Exception{
        this.roleService.addPermissionToRole(roleId, permissionIds);
        return "redirect:findAll.do";
    }

    @GetMapping("findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String roleId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(roleId);
        mv.addObject("role", role);
        mv.setViewName("role-show");
        return mv;
    }

    @GetMapping("deleteRole.do")
    public String deleteRole(@RequestParam(name="id", required = true) String roleId) throws Exception {
        roleService.deleteRoleById(roleId);
        return "redirect:findAll.do";
    }
}
